package middleware

import (
	"errors"

	"gitee.com/go-mod/framework/response"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var s error
				switch e := err.(type) {
				case error:
					s = e
				case string:
					s = errors.New(e)
				default:
					s = errors.New(cast.ToString(e))
				}
				response.Error(c, s)
				c.Abort()
			}
		}()
		c.Next()
	}
}
